<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { formSchema } from './dept.data';
  import { apiGetDeptTreeList, apiUpdateDept, apiCreateDept } from '@/api/sys/dept';
  import { UpdateDeptReq, DeptTreeListItem } from '@/api/sys/model/deptModel';

  defineOptions({ name: 'DeptModal' });

  const emit = defineEmits(['success', 'register']);

  const isUpdate = ref(true);

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;

    if (unref(isUpdate)) {
      setFieldsValue({
        ...data.record,
      });
    }
    const treeData = await apiGetDeptTreeList();
    treeData.unshift({ dept_name: '顶级部门', dept_id: 0 } as DeptTreeListItem);
    updateSchema({
      field: 'parent_id',
      componentProps: { treeData },
    });
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

  async function handleSubmit() {
    try {
      const values = (await validate()) as UpdateDeptReq;
      setModalProps({ confirmLoading: true });
      // TODO custom api
      values.dept_id = parseInt(values.dept_id);
      values.sort = parseInt(values.sort);
      console.log('values', values);
      if (unref(isUpdate)) {
        apiUpdateDept(values)
          .then(() => {
            closeModal();
            emit('success', '更新部门成功');
          })
          .catch((err) => {
            console.log('updateDept', err);
          });
      } else {
        apiCreateDept(values)
          .then(() => {
            closeModal();
            emit('success', '新建部门成功');
          })
          .catch((err) => {
            console.log('createDept', err);
          });
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
